<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Exchange extends Model
{
    protected $table = 'yt_exchange';

    protected $fillable = [
        'origin',
        'medium',
        'medium_rate',
        'usd',
        'currency',
        'value',
        'term',
        'version_date',
    ];

//    use \App\Traits\OperationLog;
    public static function boot()
    {
        parent::boot();
//        self::deleteLog();

    }


    /**
     * 获取货币对应1美元的汇率
     * @return array
     */
    public function getExchangeRates()
    {
        $currencys = config('yt.currency');
        $rates = $this->whereIn('currency',$currencys)->orderBy('id','desc')->pluck('value','currency');
        return $rates ? $rates->toArray() : [];
    }

    public static function exchangeRateByCurrency($date, $currency)
    {
        return Cache::Remember('rate:' . $date . $currency, config('constants.CACHE_EXPIRES'), function () use ($date, $currency) {
            return self::where(['term' => $date , 'origin' => $currency])->first(['value']);
        });
    }

    public static function exchangeFactorByCurrency($date, $currency)
    {
        return Cache::Remember('rateFactor:' . $date . $currency, config('constants.CACHE_EXPIRES'), function () use ($date, $currency) {
            return self::where(['term' => $date , 'currency' => $currency])->first(['value']);
        });
    }
}
